package gengine.clientside.console;

import gengine.clientside.ClientApplication;
import gengine.common.console.BaseConsole;
import gengine.common.console.CmdProcessor;
import gengine.common.packets.MessagePacket;

/**
 * User: arseniy
 * Date: 26.12.11
 */
public class ClientConsole extends BaseConsole {
    ClientApplication app = ClientApplication.getApplication();

    public ClientConsole() {
        super();
        registeredCommands.put("connect", new Cl_Connect());
        registeredCommands.put("disconnect", new Cl_Disconnect());
        registeredCommands.put("say", new Cl_Say());
        registeredCommands.put("tell", new Cl_Tell());
        registeredCommands.put("quit",new CmdQuit());
        registeredCommands.put("exit",new CmdQuit());
        registeredCommands.put("name",(e)->{
            app.clientInfo.setName(e[1]);
            app.sendClientInfo();
            return "";
        });
        storage.add("connect localhost:18600");
    }

    private class Cl_Connect implements CmdProcessor {
        @Override
        public String process(String[] args) {
            return args.length > 1 ? app.connect(args[1]) : "Incorrect usage";
        }
    }

    private class Cl_Disconnect implements CmdProcessor {
        @Override
        public String process(String[] args) {
            return app.disconnect() ? "Disconnected" : "Not connected";
        }
    }

    private class Cl_Say implements CmdProcessor {
        @Override
        public String process(String[] args) {
            return send(args, 0, 1);
        }

        protected String send(String[] args, int targetId, int msgOffset) {
            if (!app.isConnected())
                return "Not connected";
            if (args.length == msgOffset)
                return "Nothing to say";
            String msg = args[msgOffset];
            for (int i = msgOffset + 1; i < args.length; i++)
                msg += " " + args[i];
            app.clientThread.sendPacketImmediately(new MessagePacket(msg, targetId));
            return "";
        }
    }

    private class Cl_Tell extends Cl_Say {
        private final static String INCORRECT_USAGE = "Incorrect usage. Usage: tell Id message";

        @Override
        public String process(String[] args) {
            if (args.length < 3)
                return INCORRECT_USAGE;
            int targetId;
            try {
                targetId = Integer.parseInt(args[1]);
            } catch (NumberFormatException e) {
                return INCORRECT_USAGE;
            }
            return send(args, targetId, 2);
        }
    }
}

